package chaw.android.train;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import chaw.android.util.HttpRequestManager;
import chaw.android.util.Preferences;
import chaw.android.util.ServerURL;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class CreateRoomActivity extends ListActivity {
	ArrayList<UserItem> data, selectedData;
	private ImageView btnClose, btnOk;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create_room);
		
		btnClose = (ImageView) findViewById(R.id.btnClose);
		btnOk = (ImageView) findViewById(R.id.btnOk);
		
		btnClose.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		btnOk.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				createRoom();
			}
		});
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		setListView();
	}
	
	private void setListView(){
		data = new ArrayList<UserItem>();
		selectedData = new ArrayList<UserItem>();
		data.clear();
		selectedData.clear();
		
		DownloadAsynkTask task = new DownloadAsynkTask();
		String[] params = new String[] { ServerURL.favoritePeople, "user_id", Preferences.getValue(getBaseContext(), "user_id")};
		task.execute(params);
	}
	
	@Override
	public void onListItemClick(ListView parent, View v, int position, long id){
		UserItem selectedItem = (UserItem) parent.getItemAtPosition(position);

		if(selectedItem.getIconId() == R.drawable.btn_add){
			data.get(position).setIconId(R.drawable.btn_reply);
			selectedData.add(selectedItem);
		}
		else{
			data.get(position).setIconId(R.drawable.btn_add);
			selectedData.remove(selectedItem);
		}
		
		getListView().setAdapter(new StationItemAdapter(getBaseContext(), R.layout.list_row, data));
	}
	
	private void createRoom(){
		List<String> chatRoomUsers = new ArrayList<String>();
		for(int i = 0; i < selectedData.size(); i ++){
			chatRoomUsers.add(selectedData.get(i).getUserId());
		}

		UploadAsynkTask task = new UploadAsynkTask();
		String[] params;
		if(getIntent().getExtras().getBoolean("isInvite"))
			params = new String[] { ServerURL.inviteUsersToRoom, "user_id_check", Preferences.getValue(getBaseContext(), "user_id"), 
				"uuid_check", Preferences.getValue(getBaseContext(), "uuid"), "json_user_ids", chatRoomUsers.toString(), "room_id", 
				getIntent().getExtras().getString("roomId"), "message", Preferences.getValue(getBaseContext(), "nick_name") + "님이 채팅방에 초대하였습니다."};
		else{
			chatRoomUsers.add(Preferences.getValue(getBaseContext(), "user_id"));
			params = new String[] { ServerURL.createRoom, "user_id_check", Preferences.getValue(getBaseContext(), "user_id"), 
				"uuid_check", Preferences.getValue(getBaseContext(), "uuid"), "json_string", chatRoomUsers.toString()};
		}
		
        task.execute(params);
	}
	
	private class DownloadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			try {
				JSONObject json_result = new JSONObject(result);
				JSONArray favoriteUsers = json_result.getJSONArray("users");
				for(int i = 0; i < favoriteUsers.length(); i++){
					JSONObject eachUser = favoriteUsers.getJSONObject(i);
					if(eachUser.getString("user_id").equalsIgnoreCase(Preferences.getValue(getBaseContext(), "user_id")))
						continue;
					UserItem eachItem = new UserItem(eachUser.getString("user_id"), eachUser.getString("nick_name"));
					data.add(eachItem);
				}
				
				getListView().setAdapter(new StationItemAdapter(getBaseContext(), R.layout.list_row, data));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private class UploadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if(getIntent().getExtras().getBoolean("isInvite")){
				finish();
			}
			else{
				try {
					JSONObject resultData = new JSONObject(result);
					String roomId = resultData.getString("room_id");
					
			        Intent chatIntent = new Intent(getBaseContext(), ChatRoomActivity.class);
					chatIntent.putExtra("roomId", roomId);
					chatIntent.putExtra("isChat", true);
					startActivity(chatIntent);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	private class StationItemAdapter extends ArrayAdapter<UserItem>{
		private ArrayList<UserItem> items;
		private int layout;
		
		public StationItemAdapter(Context ctx, int rsrcId, ArrayList<UserItem> data){
			super(ctx, rsrcId, data);
			this.items = data;
			this.layout = rsrcId;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent){
			View v = convertView;
			if(v == null){
				LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(layout, null);
			}
			UserItem e = items.get(position);
			if(e != null){
				((TextView)v.findViewById(R.id.label)).setText(e.getUserName());
				((ImageView)v.findViewById(R.id.icon)).setImageResource(e.getIconId());
			}
			return v;
		}
	}
	
	private class UserItem{
		private String userId, userName;
		private int iconId;
		
		public UserItem(String initId, String initName){
			userId = initId;
			userName = initName;
			iconId = R.drawable.btn_add;
		}

		public String getUserId() {
			return userId;
		}
		
		public String getUserName() {
			return userName;
		}
		
		public int getIconId() {
			return iconId;
		}
		
		public void setIconId(int iconId){
			this.iconId = iconId; 
		}
	}
}
